package com.qf.springbootproject.index.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.springbootproject.index.entity.Category;
import com.qf.springbootproject.index.mapper.CategoryMapper;
import com.qf.springbootproject.index.service.CategoryService;
import com.qf.springbootproject.index.entity.Product;
import com.qf.springbootproject.index.entity.ProductImg;
import com.qf.springbootproject.index.service.ProductImgService;
import com.qf.springbootproject.index.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author yyq
 * @since 2023-02-14
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    ProductService productService;
    @Autowired
    ProductImgService productImgService;

    /**
     * 分类列表
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> categoryList() {
        //查询所有一级分类信息
        List<Category> firstCategoryList = list(new QueryWrapper<Category>().eq("parent_id", 0));
        //遍历所有查询到的一级分类，填充二级分类数据
        for (Category category : firstCategoryList) {
            //获取当前一级分类Id
            Integer categoryId = category.getCategoryId();
            //查询当前Id下有哪些二级分类
            List<Category> secondCategoryList = list(new QueryWrapper<Category>().eq("parent_id", categoryId));
            //遍历secondCategoryList,为每个二级分类对象填充三级分类数据
            for (Category sec : secondCategoryList) {
                //获取二级分类Id
                Integer categoryId1 = sec.getCategoryId();
                List<Category> thirdCategoryList = list(new QueryWrapper<Category>().eq("parent_id", categoryId1));
                //把查询出来的三级分类，设置到二级分类对象中
                sec.setCategories(thirdCategoryList);
            }
            //把查询出来的二级分类，设置到一级分类对象中
            category.setCategories(secondCategoryList);
        }
        return firstCategoryList;
    }

    /**
     * 销量商品分类
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> CategoryProducts() {
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("category_level", 1);
        List<Category> list = list(categoryQueryWrapper);
        for (Category category : list) {
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("root_category_id", category.getCategoryId())
                    .orderByDesc("sold_num").last("limit 0,6");
            List<Product> productList = productService.list(productQueryWrapper);
            category.setProducts(productList);
            for (Product product : productList) {
                QueryWrapper<ProductImg> productImgQueryWrapper = new QueryWrapper<>();
                String productId = product.getProductId();
                productImgQueryWrapper.eq("item_id", productId);
                List<ProductImg> list1 = productImgService.list(productImgQueryWrapper);
                product.setImgs(list1);
            }
        }
        return list;
    }


    /**
     * 分类列表优化版
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> categoryListRecursive() {
        //查询全表的分类信息
        List<Category> all = list();
        //通过stream的filter方法，获取到顶级分类
        List<Category> firstList = all.stream().filter(category -> category.getParentId().equals(0)).collect(Collectors.toList());
        //给当前的分类信息填充下级分类信息
        populateChild(firstList, all);


        return firstList;
    }


    /**
     * 分类列表递归方法
     * 给传入的list中的所有分类对象填充下级分类
     *
     * @param list:
     * @param all:全部分类数据
     */
    public void populateChild(List<Category> list, List<Category> all) {
        //给当前分类list中的所有分类对象填充下属的二级分类信息
        for (Category category : list) {
            Integer categoryId = category.getCategoryId();
            //过滤all，保留parentId=categoryId的数据，就是当前需要的下级分类数据
            List<Category> child = all.stream().filter(c -> c.getParentId().equals(categoryId)).collect(Collectors.toList());
            if (child != null && child.size() > 0) {
                populateChild(child, all);
            }
            category.setCategories(child);
        }
    }

    public void populateImg(List<Product> productList) {
        for (Product product : productList) {
            List<ProductImg> productImgList = productImgService.list(new QueryWrapper<ProductImg>().eq("item_id", product.getProductId()));
            product.setImgs(productImgList);
        }
    }


    /**
     * 销量商品分类代码优化
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> CategoryRecommends() {
        //1.查顶级分类信息
        List<Category> firstCategory = list(new QueryWrapper<Category>().eq("parent_id", 0));
        //2.把需要使用到的商品信息一次性查询出来
        //2.1 List<Category> --->List<CategoryId>
        List<Integer> categoryIdList = firstCategory.stream().map(new Function<Category, Integer>() {
            @Override
            public Integer apply(Category category) {
                return category.getCategoryId();
            }
        }).collect(Collectors.toList());
        //2.2查询商品信息
        List<Product> productList = productService.list(new QueryWrapper<Product>().in("root_category_id", categoryIdList));
        //3.把productList中的商品图片信息填充上
        populateImg(productList);
        //4.List<Product> ---> Map
        Map<Integer, List<Product>> map = productList.stream().collect(Collectors.groupingBy(Product::getRootCategoryId));
        //获取map中的key
        Set<Integer> categoryIdSet = map.keySet();
        //List<Category> firstCategoryList = firstCategory.stream().filter(c -> categoryIdSet.contains(c.getCategoryId())).collect(Collectors.toList());
        List<Category> firstCategoryList = firstCategory.stream().filter(category -> categoryIdSet.contains(category.getCategoryId())).collect(Collectors.toList());
        //5.商品信息挂到Category对象中
        for (Category category : firstCategoryList) {
            Integer categoryId = category.getCategoryId();
            List<Product> products = map.get(categoryId);
            //把product按照销量倒叙，取前6个
            List<Product> sortedProductList = products.stream().sorted((o1, o2) -> o2.getSoldNum() - o1.getSoldNum()).limit(6).collect(Collectors.toList());
            category.setProducts(sortedProductList);
        }
        return firstCategoryList;
    }
}














